package com.edu.controller;

import com.edu.dao.ProductCategoryMapper;
import com.edu.dao.ProductMapper;
import com.edu.data.Product;
import com.edu.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

@Controller
@RequestMapping("/upload")
public class UploadController {
    SqlSession sqlSession= MyBatisUtil.createSession();
    ProductMapper productMapper=sqlSession.getMapper(ProductMapper.class);
    ProductCategoryMapper productCategoryMapper=sqlSession.getMapper(ProductCategoryMapper.class);

    @RequestMapping("/upLoads")
    public String upLoad(HttpServletResponse resp, HttpServletRequest req, Product product) throws IOException {
        if (product==null || product.getEpName().trim().equals("")){
            return "redirect:/product/toProduct";
        }
        //转换成多部分request对象
        MultipartHttpServletRequest mreq = (MultipartHttpServletRequest) req;
        //获得文件对象
        MultipartFile file = mreq.getFile("photo");
        product.setEpcId(productCategoryMapper.selectByPrimaryKey(product.getEpcChildId()).get(0).getEpcParentId());

        if (!file.isEmpty() && file != null){
            //获得上传文件名
            String fileName = file.getOriginalFilename();
            product.setEpFileName(fileName);
            System.out.println(req.getServletContext().getRealPath("/")+ "/static/files/"+fileName);
            System.out.println(req.getServletContext().getContextPath()+ "/static/files/"+fileName);
            //以流的形式写入文件
//            FileOutputStream fos = new FileOutputStream(req.getContextPath()+ "/static/files/"+fileName);
//            fos.write(file.getBytes());
//            fos.flush();
//            fos.close();
        }

        if (product.getEpId() != null){
            productMapper.updateByPrimaryKeySelective(product);
        }else {
            productMapper.insertSelective(product);
        }

        return "redirect:/product/toProduct";
    }
}
